package com.hy.service.impl;


import com.hy.entitys.Chapter;
import com.hy.entitys.StoryEntity;
import com.hy.entitys.WebStorageEntity;
import com.hy.mapper.StoryMapper;
import com.hy.service.StoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hy.service.WebStorageService;
import com.hy.utils.StoryUtils;


import org.apache.commons.io.IOUtils;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhanghongyang
 * @since 2019-06-16
 */
@Service
public class StoryServiceImpl extends ServiceImpl<StoryMapper, StoryEntity> implements StoryService {
    //注入网站仓库服务
    @Autowired
    public WebStorageService webStorageService;
    //声明小说工具对象
    private final StoryUtils storyUtils = new StoryUtils();

    public String saveStoryAll(StoryEntity story){
        StringBuffer path = new StringBuffer();
        //path.append(this.getClass().getResource("").getPath().split("com")[0]+"static");
       if(story!=null) {
           //path.append(this.getClass().getResource("").getPath().split("com")[0]+"static/"+story.getName()+".zip");
           path.append("/var/ftp/pub/"+story.getName()+".zip");
                    Integer integer = baseMapper.selectByName(story.getName());
                    if (integer==null||integer==1){
                        int i=0;
                        if(integer==null){
                            i = baseMapper.saveStory(story);
                            //修改小说存放地址
                            story.setSaveUrl("ftp://139.199.107.121/pub/"+story.getName()+".zip");
                        }else {
                            if(integer==1){ i = baseMapper.upDataStoryStatus(story);}
                        }

                        if (i==1) {
                            //保存小说到数据库,状态为0下载中
                            List<String> all = new ArrayList<>();

                            //获取支持库
                            WebStorageEntity web = webStorageService.getById(story.getWebStorageId());
                            //获取章节集合
                            List<Chapter> chapters = storyUtils.getChapter(story.getChapterUrl(), web.getChapterSelect());

                            chapters.forEach(chapter->{

                                Elements crawl = storyUtils.crawl(chapter.getUrl(), web.getContentSelect(), null);

                                crawl.forEach(e -> {

                                    all.add(chapter.getName());
                                    String s = e.html().replaceAll("<br>", "\r\n");
                                    s=s.replaceAll("&nbsp;&nbsp;&nbsp;&nbsp;", "    ");
                                    s=s.replaceAll("<script>chaptererror();</script>"," ");
                                    all.add(s);
                                    try {
                                        // OutputStream os = new FileOutputStream(story.getName()+".txt",true);
                                        //创建zip输出流
                                        ZipOutputStream out = new ZipOutputStream( new FileOutputStream(path.toString(),true));
                                        out.putNextEntry(new ZipEntry(story.getName()+".txt"));
                                        IOUtils.writeLines(all, IOUtils.LINE_SEPARATOR,out);
                                        out.close();
                                    } catch (IOException e1) {

                                        e1.printStackTrace();
                                    }
                                });

                            });
                            story.setStatus(1);
                            int j = baseMapper.upDataStoryStatus(story);
                        }else {
                            log.error("修改更新小说失败"+story.toString());
                        }

                    }else {
                        log.error("小说正在更新中"+story.toString());
                        return "";
                    }

        }
        log.error("更新小说成功"+story.toString());
        return path.toString();
    }

    @Override
    public List<StoryEntity> selectStoryByName(String name) {

        return baseMapper.selectByNameE(name);
    }
}
